package com.eascs.web.o2o.web.aging.dubbo;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.common.service.IO2oLoanapplyDubboService;
import com.eascs.admin.common.vo.O2oLoanapplyInfo;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.web.o2o.web.aging.dao.ProcessTaskMainDao;
import com.eascs.web.o2o.web.aging.dao.ProcessTaskNodeDao;
import com.eascs.web.o2o.web.aging.entity.AgingExportEntity;
import com.eascs.web.o2o.web.aging.entity.DevLoanapply;
import com.eascs.web.o2o.web.aging.entity.ProcessTaskMain;
import com.eascs.web.o2o.web.aging.entity.ProcessTaskNode;
import com.eascs.web.o2o.web.aging.service.AgingDubboService;
import com.eascs.web.o2o.web.aging.service.IAgingService;



@Service
public class AgingDubboServiceImpl implements AgingDubboService {
	
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	/*@Autowired
	IAgingDevService agingDevService;*/
	@Autowired
	IAgingService agingService;
	
	@Reference
	IO2oLoanapplyDubboService o2oLoanapplyService;
	
	@Autowired
	ProcessTaskNodeDao processTaskNodeDao;
	@Autowired
	ProcessTaskMainDao processTaskMainDao;
	
	private final static int pageSize=50;
	/**
	 * 同步贷款单
	 */
	/*@Override
	public ModelResult<Boolean> insertLoanapply() {
		logger.info("开始同步贷款单 ");
		new Thread(new Runnable() {
			@Override
			public void run() {
				int pageIndex=0;
				boolean flag=true;
				try {
					logger.info("开始删除历史数据");
					agingDevService.deleteLoanApply();
					logger.info("结束删除历史数据");
					while (flag) {
						List<O2oLoanapplyInfo> data =null;
						try {
							PageResult<O2oLoanapplyInfo> loanapplyInfo = o2oLoanapplyService.getLoanapplyInfo(pageSize,pageIndex);
							data = loanapplyInfo.getData();
							logger.info("同步页数pageIndex:"+pageIndex+",dataSize:"+data.size());
							if (data.size() > 0) {
								for (int i = 0, len = data.size(); i < len; i++) {
									DevLoanapply entity = copyProperties(data.get(i));
									ModelResult<Boolean> insert = agingDevService.insertLoanapply(entity);
									if (!(insert.isSuccess() && insert.getModel())) {
										logger.info("贷款单同步失败，贷款单号【{}】", entity.getBillCode());
									}
								}
							}
						} catch (Exception e) {
							logger.error("同步贷款单失败 :",e);
							e.printStackTrace();
						}
						
						if(data != null && data.size() == pageSize)
							flag = true;
						else
							flag = false;
						pageIndex++;
					}
				} catch (Exception e) {
					logger.error("同步贷款单失败 :",e);
					e.printStackTrace();
				}
			}
		}).start();
		logger.info("结束同步贷款单 ");
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}
	*//**
	 * 同步主流程数据
	 *//*
	@Override
	public ModelResult<Boolean> insertWorkFlow() {
		ModelResult<Boolean> modelResult = agingDevService.deleteWorkflow();
		if(!modelResult.isSuccess()||!modelResult.getModel()){
			logger.info("旧工作流删除失败", "deleteWorkFlowFailure");
			
		}
		else{
		List<WorkFlowEntity> data = agingService.getWorkFlow().getData();
		for (int i = 0, size = data.size(); i < size; i++) {
			agingDevService.insertWorkFlow(data.get(i));
		}
		return modelResult.withModel(Boolean.TRUE);
		}
		return null;
	}
	*//**
	 * 同步流程节点
	 *//*
	@Override
	public ModelResult<Boolean> insertNode() {
		ModelResult<Boolean> modelResult = agingDevService.deleteNode();
		if (!modelResult.isSuccess()||!modelResult.getModel())
		{
			logger.info("旧结点删除失败", "deleteNodeFailure");
			
		}
		else{
		List<NodeEntity> data = agingService.getNode().getData();
		for (int i = 0, len = data.size(); i < len; i++) {
			agingDevService.insertNode(data.get(i));
		}
		
		return modelResult.withModel(Boolean.TRUE);
		}
		return null;
	}
	
	
	
	*/
	
	/**
	 * 同步时效导出表
	 */
	/*@Override
	public ModelResult<Boolean> syncAgingExport() {
		int _pageSize=20;
		
		logger.info("开始时效导出数据");
		new Thread(new Runnable() {
			@Override
			public void run() {
				int pageIndex=0;
				boolean flag=true;
				try {
					logger.info("开始删除历史数据");
					agingDevService.deleteAgingExport();
					logger.info("结束删除历史数据");
					
					List<O2oLoanapplyInfo> data = null;
					while (flag) {
						try {
							PageResult<O2oLoanapplyInfo> loanapplyInfo = o2oLoanapplyService.getAgingExportLoanInfo(_pageSize,pageIndex);
							data = loanapplyInfo.getData();
							logger.info("同步页数pageIndex:"+pageIndex+",dataSize:"+data.size());
							if (data.size() > 0) {
								for (int i = 0, len = data.size(); i < len; i++) {
									AgingExportEntity vo=new AgingExportEntity();
									org.springframework.beans.BeanUtils.copyProperties(data.get(i), vo);
									//排除历史单、流程不全的数据， eg: BM_O2O1607-0061  开头已O2O的
									String title = null;
									try {
										title = vo.getBillCode().substring(0, 3);
									} catch (Exception e) {
										logger.info("获取贷款单号错误:"+vo.getLoanapplyNo()+", bill-code:"+vo.getBillCode());
										continue;
									}
									if(StringUtils.equals(title, "O2O")){
										logger.info("排除历史单   贷款单号:"+vo.getLoanapplyNo()+", bill-code:"+vo.getBillCode());
										continue;
									}
									
									List<ProcessTaskNode> nodeList=processTaskNodeDao.getTaskNodeListByReferId(vo.getLoanapplyNo());
									Map<String, List<ProcessTaskNode>> nodeMap=new HashMap<>();
									for (ProcessTaskNode node : nodeList) {
										String key=node.getTaskId();
										List<ProcessTaskNode> value=nodeMap.get(key);
										if(value == null){
											value=new ArrayList<>();
											nodeMap.put(key, value);
										}
										value.add(node);
									}
									
									List<ProcessTaskMain> mainList=processTaskMainDao.getTaskMainListByReferId(vo.getLoanapplyNo());
									agingCalc(mainList,nodeMap,vo);
									
									ModelResult<Boolean> insert = agingDevService.insertAgingExport(vo);
									if (!(insert.isSuccess() && insert.getModel())) {
										logger.info("贷款单同步失败，贷款单号【{}】", vo.getBillCode());
									}
								}
							}
						} catch (Exception e) {
							logger.error("同步贷款单失败 :",e);
							e.printStackTrace();
						}
						
						if(data != null && data.size() == _pageSize)
							flag = true;
						else
							flag = false;
						pageIndex++;
					}
				} catch (Exception e) {
					logger.error("同步贷款单失败 :",e);
					e.printStackTrace();
				}
			}
		}).start();
		logger.info("结束时效导出数据");
		return new ModelResult<Boolean>().withModel(Boolean.TRUE);
	}*/
	
	
	
	public void agingCalc(List<ProcessTaskMain> mainList,Map<String, List<ProcessTaskNode>> nodeMap,AgingExportEntity vo){
		List<ProcessTaskNode> temp;
		for (ProcessTaskMain main : mainList) {
			temp = nodeMap.get(main.getTaskId());
			for (ProcessTaskNode item : temp) {
				String nodeName = item.getNodeName();
				float timeEff = item.getTimeEffective() == null? 0 : item.getTimeEffective();
				float usedTime = item.getUsedTime() == null ? 0 : item.getUsedTime();
				float overTime=usedTime - timeEff > 0 ? usedTime - timeEff : 0;
				if(StringUtils.equals(main.getProcessType(), "CREDIT")){//征信调查
					switch (nodeName) {
					case "平台财务":
						vo.setCwsh_setup1(overTime); //老数据--财务审核是征信流程一个子节点
						break;
					case "总部征信送审":
						vo.setZx_setup1(overTime);
						break;
					case "总部风险经理":
						vo.setZx_setup2(overTime);
						break;
					case "总部风险总监":
						vo.setZx_setup3(overTime);
						break;
					default:
						break;
					}
				}else if(StringUtils.equals(main.getProcessType(), "INAUDIT")){//内部审批
					switch (nodeName) {
					case "平台信贷经理":
						vo.setNs_setup1(overTime);
						break;
					case "平台总经理":
						vo.setNs_setup2(overTime);
						break;
					case "省区风控经理（省区金融专员）":
						vo.setNs_setup3(overTime);
						break;
					case "省区金融总监（省区财务总监）":
						vo.setNs_setup4(overTime);
						break;
					case "总部风险经理":
						vo.setNs_setup5(overTime);
						break;
					case "总部风险总监":
						vo.setNs_setup6(overTime);
						break;
					default:
						break;
					}
					
				}else if(StringUtils.equals(main.getProcessType(), "BANK_REPORT")){//面签提报
					switch (nodeName) {
					case "平台信贷经理":
						vo.setMqtb_setup1(overTime);
						break;
					case "省区风控经理（省区金融专员）":
						vo.setMqtb_setup2(overTime);
						break;
					case "银行申报审查":
						vo.setMqtb_setup3(overTime);
						break;
					case "总部贷后管理":
						vo.setMqtb_setup4(overTime);
						break;
					default:
						break;
					}
					
				}else if(StringUtils.equals(main.getProcessType(), "DEPOSIT")){//保证金管理费
					switch (nodeName) {
					case "平台信贷经理":
						vo.setBzj_setup1(overTime);
						break;
					case "总部财务初审":
						vo.setBzj_setup2(overTime);
						break;
					default:
						break;
					}
					
				}else if(StringUtils.equals(main.getProcessType(), "FINANCE_AUDIT")){//平台财务
					if(StringUtils.equals(nodeName, "平台财务"))
						vo.setCwsh_setup1(overTime);
				}
			}
		}
		
		float zx_sum = covertFloat(vo.getZx_setup1()) + covertFloat(vo.getZx_setup2()) + covertFloat(vo.getZx_setup3());
		vo.setZx_sum(zx_sum);
		
		float ns_sum = covertFloat(vo.getNs_setup1()) + covertFloat(vo.getNs_setup2()) + covertFloat(vo.getNs_setup3()) + covertFloat(vo.getNs_setup4()) + covertFloat(vo.getNs_setup5()) + covertFloat(vo.getNs_setup6());
		vo.setNs_sum(ns_sum);
		
		float mqtb_sum = covertFloat(vo.getMqtb_setup1()) + covertFloat(vo.getMqtb_setup2()) + covertFloat(vo.getMqtb_setup3()) + covertFloat(vo.getMqtb_setup4());
		vo.setMqtb_sum(mqtb_sum);
	
		float bzj_sum = covertFloat(vo.getBzj_setup1()) + covertFloat(vo.getBzj_setup2());
		vo.setBzj_sum(bzj_sum);
		
		float yhsb_sum = zx_sum + ns_sum + mqtb_sum - covertFloat(vo.getMqtb_setup4());
		vo.setYhsb_sum(yhsb_sum);
		
		float sum = zx_sum + ns_sum + mqtb_sum + bzj_sum + covertFloat(vo.getCwsh_setup1());
		vo.setSum(sum);
		
		String loanType;
		switch (vo.getLoanType()) {
			case "BK":
				loanType = "终端贷";
				break;
			case "EA":
				loanType = "接力贷";
				break;
			case "FQ":
				loanType = "分期贷";
				break;
			case "BP":
				loanType = "品牌贷";
				break;
			default:
				loanType = "终端贷";
				break;
		}
		vo.setLoanType(loanType);
	}
	
	public float covertFloat(Float f){
		return f==null ? 0 : f;
	}
	
	public DevLoanapply copyProperties(O2oLoanapplyInfo info) {
		DevLoanapply entity = new DevLoanapply();
		entity.setLoanapplyNo(info.getLoanapplyNo());
		entity.setBillCode(info.getBillCode());
		entity.setLtd(info.getLtd());
		entity.setLtdName(info.getLtdName());
		entity.setOperatorName(info.getOperatorName());
		entity.setOperatorNo(info.getOperatorNo());
		entity.setProvinceName(info.getProvinceName());
		entity.setProvinceCode(info.getProvinceCode());
		entity.setWfType(info.getWfType());
		entity.setCreateDate(info.getCreateDate());
		return entity;
	}

}
